#coding=utf8
import glgui2
import Map
import GameLogic
import pyglet
from pyglet.gl import *
import sqlite_utils
import Mission


class EditorMenu:
  
  def hide(self):
    self.layout.visible = False
    glgui2.common_signals.set_block('events/mouse/mouse_press',self.on_mouse_down,True)
    self.map.visible = False
  def show(self):
    self.layout.visible = True
    self.menu.visible = False
    self.map.visible = True
    glgui2.common_signals.set_block('events/mouse/mouse_press',self.on_mouse_down,False)
  
  def show_menu(self,sender):
      self.menu.visible = True
  
  def hide_menu(self,sender):
      self.menu.visible = False
      
  def return_to_main(self,sender):
       self.back_to_main.transmit(None)
       
  def on_menu_click(self,button):
    self.edit_mode = 'terrain'
    self.code = int(button.name.replace('editor/terrain',''))

  def update_menus(self):
    pidx = self.company_selector.selection[0]
    imgs = []
    for group in self.mission.sides[self.side].companies[pidx].groups:
      imgs.append(self.mission.iconset.dictionary[group.type])
    self.company_groups_selector.set_elements(imgs)
    
    if len(self.company_groups_selector.selection)>0:
      platoon =  self.mission.sides[self.side].companies[self.company_selector.selection[0]].groups[self.company_groups_selector.selection[0]]
      for group in platoon.groups:
        imgs.append(self.mission.iconset.dictionary[group.type])
      self.fireteam_selector.set_elements(imgs)
    else:
      self.fireteam_selector.clear()
      
    
    
  def on_mouse_down(self,x,y,buttons,mods):
    if self.layout.hit_test(x,y):
      return
    if buttons & pyglet.window.mouse.RIGHT:
      self.mission.remove_fireteams(self.mission.selection)
      self.update_menus()
      
    if buttons & pyglet.window.mouse.LEFT and mods & pyglet.window.key.MOD_SHIFT: 
      if self.edit_mode == 'terrain':
        pos = self.map.set_code(x,y,self.code)
      elif self.edit_mode =='fireteam_placing':
        val = sqlite_utils.get_line("""SELECT name FROM fireteams""")[self.fireteam_chooser.selection[0]]
        platoon = None
        idx = None
        if len(self.company_groups_selector.selection)==1:
          platoon =  self.mission.sides[self.side].companies[self.company_selector.selection[0]].groups[self.company_groups_selector.selection[0]]
          idx = self.company_selector.selection[0]
          if platoon.__class__.__name__ != 'Platoon':
            platoon = None
            
        fireteam  = self.mission.add_fireteam(self.side,self.company_selector.selection[0],val,x,y,platoon)
        
        self.company_groups_selector.set_elements(self.company_groups_selector.elements+self.mission.iconset.get_images([val]))
        self.update_menus()
        if not idx is None:
          self.company_groups_selector.set_selection(idx)
        
      elif self.edit_mode =='platoon_placing':
        val = sqlite_utils.get_line("""SELECT name FROM platoons""")[self.platoon_chooser.selection[0]]
        platoon = self.mission.add_platoon(self.side,self.company_selector.selection[0],val,x,y)
        self.update_menus()
        self.company_groups_selector.set_selection(len(self.company_groups_selector.elements)-1)
        
        
      
  
  def show_menu(self,sender):
      self.menu.visible = True
  
  
  def hide_menu(self,sender):
      self.menu.visible = False
      
  def return_to_main(self,sender):
       self.back_to_main.transmit(None)
  
  def save_map(self,sender):
    self.map.save('test.map')
    self.menu.visible = False
  
  def load_map(self,sender):
    self.map.read('test.map')
    self.menu.visible = False
    self.update_menus()
    
  def save_mission(self,sender):
    self.mission.write('test.mis')
    self.menu.visible = False
  
  def load_mission(self,sender):
    self.mission.read('test.mis')
    self.menu.visible = False
    self.update_menus()
  
  def set_side(self,value):
    self.side = value
    self.update_menus()
  
  
  def select_company(self,value):
    self.company = value
    
  def select_platoon(self,value):
    self.fireteam_chooser.clear_selection()
    self.edit_mode = 'platoon_placing'
  
  def choose_fireteam(self,value):
    self.platoon_chooser.clear_selection()
    self.edit_mode = 'fireteam_placing'
    
  def update_command_listboxes(self):
    pass
  
  def add_fireteam(self,value):
    pass
  
  def group_selected(self,selection):
  
    if len(selection) == 0:
      self.mission.clear_selection()
      self.fireteam_selector.clear()
      return
    group = self.mission.sides[self.side].companies[self.company_selector.selection[0]].groups[self.company_groups_selector.selection[0]]
    if group.__class__.__name__ == 'Platoon':
      self.mission.clear_selection()
      ft_images = []
      self.mission.select_fireteams(group.groups)
      for ft in group.groups:
        ft_images.append(self.mission.iconset.dictionary[ft.type])
      self.fireteam_selector.set_elements(ft_images)
      self.fireteam_selector.select_all()
    if group.__class__.__name__ == 'Fireteam':
      self.mission.clear_selection()
      self.mission.select_fireteam(group)
      
    
  def fireteam_selected(self,selection):
    if not (len(self.company_selector.selection)> 0 and  len(self.company_groups_selector.selection)>0 ): return
    group = self.mission.sides[self.side].companies[self.company_selector.selection[0]].groups[self.company_groups_selector.selection[0]]
    if group.__class__.__name__!='Platoon': return
    
    self.mission.clear_selection()
    flist = filter( lambda x: group.groups.index(x) in selection, group.groups)
    self.mission.select_fireteams(flist)
    
    
  
  def company_selected(self,selection):
    self.group_selected([])
    self.update_menus()
    
  #IN HERE
  def __init__(self):
    self.layout = glgui2.Layout((1024,768))
    #default code
    self.code = 1
  
    self.map = Map.Map('first',(32,32))
    self.mission = Mission.Mission(self.map)
    self.edit_mode = 'terrain'#'units','objectives','structures'
    print self.map.hexfield.pos
    #DEFINING: terrain editing menu
    self.terrain_menu = glgui2.Frame('graphics/menu',u'Меню',pos = (50,570),size = (150,140),layout = glgui2.GridLayout(size = (150,140),tsize = (3,3)))
    self.texture_grid = pyglet.image.ImageGrid(pyglet.image.load("graphics/hextiles.png"),1,8)
    for a in range(8):
      spr =( self.texture_grid[a])
      self.terrain_menu.layout.add_widget(glgui2.PictureButton('editor/terrain'+str(a),spr,size = (40,40)))
      glgui2.common_signals.connect_to_channel('gui_events/on_click/editor/terrain'+str(a),self.on_menu_click)
    self.layout.add_widget(self.terrain_menu)
    #END: terrain editing menu
    
    #DEFINING: units editing menu
    print 
    self.batallion_menu = glgui2.Frame('graphics/units',u'Отряды',pos = (50,200),size = (150,250),layout = glgui2.CentralLayout((150,250)))
    self.sides = glgui2.Combobox('sides',zip(*sqlite_utils.sql_exec('SELECT name from sides'))[0],size=(120,20))
    self.fireteam_chooser = glgui2.HListBox('editor/fireteam_chooser',self.mission.iconset.get_images(sqlite_utils.get_line("""SELECT name FROM fireteams""")))
    self.platoon_chooser = glgui2.HListBox('editor/platoon_chooser',self.mission.iconset.get_images(sqlite_utils.get_line("""SELECT name FROM platoons""")))
    self.platoon_chooser.clear_selection()
    glgui2.common_signals.connect_to_channel('gui_events/on_selection_changed/editor/platoon_chooser',self.select_platoon)
    glgui2.common_signals.connect_to_channel('gui_events/on_selection_changed/editor/fireteam_chooser',self.choose_fireteam)
    
    self.batallion_menu.layout.add_widget(self.sides)
    self.batallion_menu.layout.add_widget(self.platoon_chooser)
    self.batallion_menu.layout.add_widget(self.fireteam_chooser)
    
    self.batallion_menu.update_rect()
    
    self.side = self.sides.current_value
    self.unit_add = ('','')
    
    glgui2.common_signals.connect_to_channel('gui_events/value_changed/sides',self.set_side)
    
    
    #self.batallion_menu.layout.add_widget(self.unit_button)
    self.batallion_menu.layout.update_rect()
    #END Usqua EDITING MENU
    
  
    self.layout.add_widget(self.batallion_menu)
    
      #Operational command frame
    
    self.fireteam_menu = glgui2.Frame('editor/fireteam',u'Отделение',pos = (50,30),size = (250,100),layout = glgui2.CentralLayout((250,100)))
    self.fireteam_menu.layout.add_widget(glgui2.Button('editor/fireteame_in_group',u'Обьеденить в группу'))
    self.fireteam_menu.layout.update_rect()
    
    #Tactical command frame
    
    self.platoon_menu = glgui2.Frame('editor/platoon',u'Взвод',pos = (320,30),size = (250,100),layout = glgui2.CentralLayout((250,100)))
    self.fireteam_selector = glgui2.HListBox('editor/fireteam_selector',[],pos = (40,60),size= (180,32),multiselect = True)
    self.platoon_menu.layout.add_widget(self.fireteam_selector)
    
    
    self.company_menu = glgui2.Frame('editor/company',u'Рота',pos = (570,30),size = (250,100),layout = glgui2.Layout((250,100)))
    self.company_selector = glgui2.HListBox('editor/company_selector',[ self.mission.iconset.dictionary['company1'], self.mission.iconset.dictionary['company2'], self.mission.iconset.dictionary['company3']],pos = (40,60),size= (180,32))
    self.company_groups_selector = glgui2.HListBox('editor/company_groups_selector',[],pos = (40,20),size= (180,32),noselect = True)
    self.company_menu.layout.add_widget(self.company_groups_selector)
    self.company_menu.layout.add_widget(self.company_selector)
  
    
    
    glgui2.common_signals.connect_to_channel('gui_events/on_selection_changed/editor/fireteam_selector',self.fireteam_selected)
    glgui2.common_signals.connect_to_channel('gui_events/on_selection_changed/editor/company_groups_selector',self.group_selected)
    glgui2.common_signals.connect_to_channel('gui_events/on_selection_changed/editor/company_selector',self.company_selected)
    
    self.layout.add_widget(self.platoon_menu)
    self.layout.add_widget(self.company_menu)
    self.layout.add_widget(self.fireteam_menu)
    self.layout.update_rect()
    
    
    
    glgui2.common_signals.connect_to_channel('events/mouse/mouse_press',self.on_mouse_down)
    
    #Menu1
    self.menu_layout = glgui2.CentralLayout((320,160))
    self.menu = glgui2.Frame('editor/menu',u'Меню',layout = self.menu_layout,pos = (350,300),size = (320,160))
    
    self.menu.layout.add_widget(glgui2.Button('editor/menu/continue',u'Продолжить'))
    glgui2.common_signals.connect_to_channel('gui_events/on_click/editor/menu/continue',self.hide_menu)
    
    
    self.menu.layout.add_widget(glgui2.Button('editor/menu/save_mission',u'Сохранить Миссию'))
    glgui2.common_signals.connect_to_channel('gui_events/on_click/editor/menu/save_mission',self.save_mission)
   
    self.menu.layout.add_widget(glgui2.Button('editor/menu/load_mission',u'Загрузить Миссию'))
    glgui2.common_signals.connect_to_channel('gui_events/on_click/editor/menu/load_mission',self.load_mission)
    
    self.menu.layout.add_widget(glgui2.Button('editor/menu/save',u'Сохранить'))
    glgui2.common_signals.connect_to_channel('gui_events/on_click/editor/menu/save',self.save_map)
   
    self.menu.layout.add_widget(glgui2.Button('editor/menu/load',u'Загрузить'))
    glgui2.common_signals.connect_to_channel('gui_events/on_click/editor/menu/load',self.load_map)
   
    self.menu.layout.add_widget(glgui2.Button('editor/menu/quit',u'Выйти'))
    glgui2.common_signals.connect_to_channel('gui_events/on_click/editor/menu/quit',self.return_to_main)
    
    self.menu.layout.update_rect()
    self.layout.add_widget(self.menu)
    
    self.hide_menu(None)
    #Endmenu1
    self.layout.add_widget(glgui2.Button('editor/show_menu',u'Меню',pos = (900,10)))
    glgui2.common_signals.connect_to_channel('gui_events/on_click/editor/show_menu',self.show_menu)
    self.back_to_main = glgui2.common_signals.create_channel('engine_events/editor/show_main_menu')
    
    self.layout.update_rect()
    
    
  def draw(self):
    self.map.draw()
    self.layout.draw()
    
